//
//  SBRecommendFoucusVc.m
//  BaiSiBuDeJie
//
//  Created by chaoyi on 16/8/24.
//  Copyright © 2016年 tsaievan. All rights reserved.
//

#import "SBRecommendFoucusVc.h"
#import "SBTjgzListModel.h"
#import "BSTjgzLeftCell.h"
#import "BSTjgzRightCell.h"
#import "MJRefreshHeader.h"
#import "BSDIYHeader.h"
#import "MJRefreshNormalHeader.h"
#import "BSGzrTopModel.h"
#import "BSGzrOtherModel.h"

@interface SBRecommendFoucusVc ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *leftTableView;//左边tableView

@property (weak, nonatomic) IBOutlet UITableView *rightTableView;//右边边tableView

@property (nonatomic,strong)NSArray *leftDataArr;//左边tableView数据

@property (nonatomic,weak)BSTjgzLeftCell *lastLeftCell;//记录上一个被点击的cell


@property (nonatomic,assign)NSInteger leftIndex;//记录左边tableView选中cell的角标

@property (nonatomic,strong)BSGzrTopModel *topModel;//推荐也模型数据

@property (nonatomic,strong)BSGzrOtherModel *otherModel;//其他的模型数据

@property (nonatomic,strong)NSMutableArray *rightData;//右边数据

@property (nonatomic,copy)NSString *baseUrlStr;//(推荐页数据基本url)

@property (nonatomic,strong)NSArray *urlArr;//处理拼接url参数的数据

@property (nonatomic,strong)NSMutableDictionary *cacheDic;//缓存

@property (nonatomic,weak)UIView *dimView;//挡住数据的view

@property (nonatomic,strong)BSDIYHeader *diyHeader;//自定义的头

@property (nonatomic,strong)NSMutableDictionary *dataArrDic;//保存全部的数据

@property (nonatomic,copy)NSString * keywordsUrl;//url关键的字

@property (nonatomic,assign)BOOL flag;//Yes 为主动点击加载数据

@property (nonatomic,strong)NSURLSessionDataTask *otherTask;

@property (nonatomic,strong)NSURLSessionDataTask *topTask;

@end

@implementation SBRecommendFoucusVc

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.leftIndex = 0;
    
    self.flag = YES;
    
    self.baseUrlStr = @"http://api.budejie.com/api/api_open.php?a=friend_recommend&appname=bs0315&asid=823107D4-D1E5-4D4B-A82F-0934ABA8B4DF&c=user&client=iphone&device=ios%20device&from=ios&jbk=0&last_coord=&last_flag=list&mac=&market=&openudid=d41d8cd98f00b204e9800998ecf8427e0e59d09b&pre=50&udid=&ver=4.3";
    
    //设置背景色
    
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.leftTableView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
    
    self.rightTableView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
    
    self.rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //设置title值
    self.navigationItem.title = @"推荐关注";
    
    //加载左边数据
    [self loadLeftData];
    
    //上拉下拉
    [self setMJRefresh];
    
}


#pragma mark ----------- 设置上下拉刷新
-(void)setMJRefresh{
    
    //下拉刷新
    BSDIYHeader *header = [BSDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    
    self.diyHeader =header;
    
    self.rightTableView.mj_header = header;
    
    [self.rightTableView.mj_header beginRefreshing];
    
    //上拉刷新
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [footer setTitle:@"向上滑动,加载更多" forState:MJRefreshStateIdle];
    [footer setTitle:@"松开加载更多" forState:MJRefreshStatePulling];
    [footer setTitle:@"加载中..." forState:MJRefreshStateRefreshing];
    [footer.stateLabel setFont:[UIFont fontWithName:@"AmericanTypewriter-Bold" size:14]];
    footer.arrowView.alpha = 0.01;
    
    self.rightTableView.mj_footer = footer;
}

#pragma mark ----------- loadData 加载数据

// 加载数据

- (void)loadData{
    
    //非拽动刷新(主动让菊花转)
    if(self.flag){
        
        self.flag = NO;
        self.dimView.hidden = NO;
        self.rightTableView.scrollEnabled = NO;
        
    }else{
        
        self.dimView.hidden = YES;
    }
    
    //清除缓存
    //---- 判断是否主动拽动刷新
    if([self.rightTableView.mj_header state] == MJRefreshStateRefreshing && !self.flag){
        
        NSMutableArray *dataArrM = [self.dataArrDic objectForKey:[NSString stringWithFormat:@"%ld",(long)self.leftIndex]];
        
        if(dataArrM.count > 0){
            //清除数据
            [dataArrM removeAllObjects];
            
        }
        
    }
    
    
    
    
    //下载数据
    SBTjgzListModel *model = self.leftDataArr[self.leftIndex];
    //判断数据类型(是否为推荐页)
    if(self.leftIndex == 0){
        
        [self.topTask cancel];
        
        self.topTask = [BSGzrTopModel loadDataWith:model.link andSuccessBlock:^(BSGzrTopModel *infoList) {
            
            self.topModel = infoList;
            
            self.rightData = [self.dataArrDic objectForKey:[NSString stringWithFormat:@"%ld",self.leftIndex]];
            NSLog(@"aa");
            [self.rightData addObjectsFromArray:infoList.top_list];
            
            
            
            //刷新数据
            [self.rightTableView reloadData];
            self.rightTableView.scrollEnabled = YES;
            self.dimView.hidden = YES;
            
            //结束刷新
            [self.rightTableView.mj_header endRefreshing];
            
        } andFailBlock:^(NSError *error) {
            
            NSLog(@"%@",error);
            
            [self.rightTableView.mj_header endRefreshing];
            
        } andNoMoreBlock:^(NSString *str) {
            
            NSLog(@"%@",str);
            [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
            
        }];
        
        
    }else{
        
        if(self.otherTask){
            
            [self.otherTask cancel];
        }
        
        self.otherTask  =  [BSGzrOtherModel loadDataWith:model.link andSuccessBlock:^(BSGzrOtherModel *infoList) {
            
            self.otherModel = infoList;
            NSLog(@"bb");
            self.rightData= [self.dataArrDic objectForKey:[NSString stringWithFormat:@"%ld",self.leftIndex]];
            
            [self.rightData addObjectsFromArray:infoList.list];
            
            
            //刷新数据
            [self.rightTableView reloadData];
            self.rightTableView.scrollEnabled = YES;
            self.dimView.hidden = YES;
            //结束刷新
            [self.rightTableView.mj_header endRefreshing];
            
        } andFailBlock:^(NSError *error) {
            
            NSLog(@"%@",error);
            
            [self.rightTableView.mj_header endRefreshing];
            
        } andNoMoreBlock:^(NSString *str) {
            
            NSLog(@"%@",str);
            [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
            
        }];
        
    }
    
    
}

//加载更多数据
- (void)loadMoreData{
    
    NSMutableArray *dataArrM = [self.dataArrDic objectForKey:[NSString stringWithFormat:@"%ld",self.leftIndex]];
    
    if(dataArrM.lastObject){
        
        if([dataArrM.lastObject isKindOfClass:[Top_List class]]){
            
            if(self.keywordsUrl == [self.topModel valueForKey:@"last_coord"] ){
                
                //没有数据,结束
                [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
                
                return;
            }else{
                
                self.keywordsUrl = [self.topModel valueForKey:@"last_coord"];
            }
            
        }else if([dataArrM.lastObject isKindOfClass:[List class]]){
            
            
            
        }
    }else{
        
        return;
    }
    
    //处理url
    
    if(!self.urlArr){
        
        self.urlArr = [self.baseUrlStr componentsSeparatedByString:@"&"];
    }
    
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.urlArr];
    
    for (NSInteger i = 0; i < arrM.count; i++) {
        
        if([arrM[i] containsString:@"last_coord="]){
            
            arrM[i] = [NSString stringWithFormat:@"last_coord=%@",self.keywordsUrl];
        }
        
    }
    
    NSString *newUrlStr = [arrM componentsJoinedByString:@"&"];
    
    
    //加载更多的数据
    
    if(self.leftIndex == 0){
        
        [BSGzrTopModel loadDataWith:newUrlStr andSuccessBlock:^(BSGzrTopModel *infoList) {
            
            if(infoList){
                
                self.topModel = infoList;
                
                self.rightData = [self.dataArrDic objectForKey:[NSString stringWithFormat:@"%ld",self.leftIndex]];
                
                [self.rightData addObjectsFromArray:infoList.top_list];
                
                
                [self.rightTableView reloadData];
                
                [self.rightTableView.mj_footer endRefreshing];
                
            }else{
                
                [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
            }
            
            
            
            
        } andFailBlock:^(NSError *error) {
            
            NSLog(@"%@",error);
            
            [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
            
        } andNoMoreBlock:^(NSString *str) {
            
            NSLog(@"%@",str);
            [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
            
        }];
        
    }else{
        
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
        
    }
    
    
}


- (void)loadLeftData{
    
    _leftDataArr = [SBTjgzListModel loadTjgzListData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}

#pragma mark ----------- tableView 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if([self.leftTableView isEqual:tableView]){
        //左tableView
        return self.leftDataArr.count;
    }else{
        
        return self.rightData.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if([self.leftTableView isEqual:tableView]){
        //--------------左tableView
        
        SBTjgzListModel *model = self.leftDataArr[indexPath.row];
        
        BSTjgzLeftCell *listCell = [BSTjgzLeftCell tjgzLeftCell:tableView];
        
        listCell.model = model;
        
        
        //设置样式
        if(indexPath.row == 0 && self.lastLeftCell == nil){
            
            //--设置样式
            
            self.lastLeftCell = listCell;
            
            self.lastLeftCell.colorView.hidden = NO;
            
            self.lastLeftCell.backgroundColor = [UIColor whiteColor];
            
        }
        
        return listCell;
        
    }else{
        //--------------右边tableView
        
        BSTjgzRightCell *cell = [BSTjgzRightCell tjgzRightCell:tableView];
        
        if([self.rightData.lastObject isKindOfClass:[List class]] || [self.rightData.lastObject isKindOfClass:[Top_List class]]){
            
            
            if(self.leftIndex == 0){
                
                Top_List *topModel = self.rightData[indexPath.row];
                
                cell.topModel = topModel;
                
                return cell;
            }else{
                
                List *otherModel = self.rightData[indexPath.row];
                
                cell.otherModel = otherModel;
                
                return cell;
            }
        }else{
            
            return cell;
        }
    }
    
}

#pragma mark ----------- tableView 代理方法---(点击cell)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if([self.leftTableView isEqual:tableView]){
        
        //防止重复点击
        if(self.leftIndex == indexPath.row){
            
            return;
        }
        
        
        //点击左边cell
        self.leftIndex = indexPath.row;
        
        //改变cell 的样式(先去除上一个cell 的样式)
        
        BSTjgzLeftCell *cell = [self.leftTableView cellForRowAtIndexPath:indexPath];
        
        self.lastLeftCell.colorView.hidden = YES;
        
        self.lastLeftCell.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
        
        cell.colorView.hidden = NO;
        
        cell.backgroundColor = [UIColor whiteColor];
        
        self.lastLeftCell = cell;
        
        //加载右边tableVew的数据
        
        //判断是否有缓存
        self.rightData = [self.dataArrDic objectForKey:[NSString stringWithFormat:@"%ld",self.leftIndex]];
        
        if(self.rightData.count > 0){
            
            if(self.leftIndex == 0){
                
                [self.topTask cancel];
                
            }else{
                [self.otherTask cancel];
            }
            
            [self.rightTableView reloadData];
            
            [self.rightTableView.mj_header endRefreshing];
            
            return;
        }else{
            //无
            [self.rightTableView.mj_header beginRefreshing];
            self.rightTableView.scrollEnabled = NO;
            self.dimView.hidden = NO;
            self.flag = YES;
            
        }
        
        
    }else{
        
        //点击右边cell
    }
    
}

#pragma mark ----------- 返回行高

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if([self.leftTableView isEqual:tableView]){
        //左tableView
        return 44;
    }else{
        //右tableView
        
        return 55;
        
    }
}

#pragma mark ----------- 懒加载


- (NSMutableDictionary *)dataArrDic{
    
    if(!_dataArrDic){
        
        _dataArrDic = [NSMutableDictionary dictionary];
        
        for (NSInteger i = 0; i < self.leftDataArr.count; i++) {
            
            [_dataArrDic setValue:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%ld",i]];
        }
    }
    
    return _dataArrDic;
}

- (NSMutableDictionary *)cacheDic{
    
    if(!_cacheDic){
        
        _cacheDic = [NSMutableDictionary dictionary];
    }
    
    return _cacheDic;
}


//蒙版
- (UIView *)dimView{
    
    if(!_dimView){
        
        CGRect frame = CGRectMake(0, 0, self.rightTableView.mj_w, self.rightTableView.mj_h);
        
        UIView *dimView = [[UIView alloc]initWithFrame:frame];
        
        [self.rightTableView addSubview:dimView];
        
        _dimView = dimView;
        
        dimView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
        
        dimView.hidden = YES;
    }
    
    return _dimView;
}






@end
